
import type { InputRef } from 'antd';
import { DeleteOutlined, EditOutlined, EyeOutlined } from "@ant-design/icons"
import { Button, Form, Input, Popconfirm, Table,Image } from 'antd';
import type { FormInstance } from 'antd/es/form';
import React, { useContext, useEffect, useRef, useState ,useMemo,Fragment} from 'react';
import * as http from "@/api/product"
import Dialog from '@/components/Dialog';

const EditableContext = React.createContext<FormInstance<any> | null>(null);
// 声明列表数据类型
interface Item {
  key: string;
  categoryImgurl:string,
  categoryName: string;
  category_id: string;
  createTime: string;
  creator:string
}

interface EditableRowProps {
  index: number;
}

const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

interface EditableCellProps {
  title: React.ReactNode;
  editable: boolean;
  children: React.ReactNode;
  dataIndex: keyof Item;
  record: Item;
  handleSave: (record: Item) => void;
}

const EditableCell: React.FC<EditableCellProps> = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef<InputRef>(null);
  const form = useContext(EditableContext)!;

  useEffect(() => {
    if (editing) {
      inputRef.current!.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({ [dataIndex]: record[dataIndex] });
  };

  const save = async () => {
    try {
      const values = await form.validateFields();

      toggleEdit();
      handleSave({ ...record, ...values });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };

  let childNode = children;

  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{ margin: 0 }}
        name={dataIndex}
        rules={[
          {
            required: true,
            message: `${title} is required.`,
          },
        ]}
      >
        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
      </Form.Item>
    ) : (
      <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={toggleEdit}>
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};

type EditableTableProps = Parameters<typeof Table>[0];

interface DataType {
  key: string;
  categoryImgurl:string,
  categoryName: string;
  category_id: string;
  createTime: string;
  creator:string
}

type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;


const ProductCategory: React.FC = () => {
  // dialog的显示隐藏
const [visible,setVisible]=useState(false)
const [dataSource, setDataSource] = useState<DataType[]>([]);

  // 请求数据
  let getCategoryData=()=>{
    http.getCategory()
    .then(res=>{
      var data=res.data.data
      setDataSource(
       ( data.map((item:any)=>{

          return {
            key:item._id,
            // categoryImgurl:item.categoryImgurl,
            categoryImgurl:<img src={item.categoryImgurl} style={{width:'50px',height:'50px'}}/>,
            categoryName:item.categoryName,
            category_id:item.category_id,
            createTime: item.createTime,
            creator:item.creator
          }
      })).reverse()
      )
    })
  }
  console.log(dataSource)
 useEffect(()=>{
  getCategoryData()
 },[])
//  删除数据
let DeleteData=(category_id:any)=>{
  http.deleteCategory(category_id)
  .then(res=>{
    if (res.data.state) {
      getCategoryData()
        alert('删除成功')
    } else {
        alert('删除失败,' + res.data.msg)
    }
  })

}
 
  // 表头部分
  const defaultColumns: (ColumnTypes[number] & { editable?: boolean; dataIndex: string })[] = [
    {
      title:"图片",
      dataIndex: 'categoryImgurl',
      
    },
    {
      title: '类目名称',
      dataIndex: 'categoryName',
      editable: true,
      
    },
    {
      title: '类目id',
      dataIndex: 'category_id',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title:"创建者",
      dataIndex:"creator"
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (value: any, record: any, index: number) =>
        dataSource.length >= 1 ? (
          <Fragment>
          <Button icon={<EyeOutlined />}>查看</Button>
          <Button icon={<EditOutlined />}>编辑</Button>
          <Button  danger icon={<DeleteOutlined />} onClick={(()=>{
            DeleteData(record.category_id)
          })}>删除</Button>
         </Fragment>
        ) : null,
    },
  ];

  const handleAdd = (props:any) => {
    setVisible(true)
  };
  const handOk=()=>{
    setVisible(false)
  }
  const handleCancel=()=>{
    setVisible(false)
  }

  const handleSave = (row: DataType) => {
    const newData = [...dataSource];
    const index = newData.findIndex(item => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    setDataSource(newData);
  };

  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };

  const columns = defaultColumns.map(col => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: DataType) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave,
      }),
    };
  });

  return (
    <div style={{height:400}}>
      <Button onClick={handleAdd} type="primary" style={{ marginBottom: 16 }}>
        点击添加
      </Button>
      <Dialog visible={visible} onOk={handOk} onCancel={handleCancel} handleGetCategory={getCategoryData}></Dialog>
      <Table
        components={components}
        rowClassName={() => 'editable-row'}
        bordered
        dataSource={dataSource}
        columns={columns as ColumnTypes}
        
      />
    </div>
  );
};

export default ProductCategory